package com.scau402.common.utils.code;

import com.scau402.common.utils.CustomRedisConfig;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class JadeCodeUtils {
    private static String KEY_NAME_PRE = "JADE_KEY_";

    public void setCurrentCodeToMax(String maxCode, String tenantCode, String userCode) {

        CustomRedisConfig cc = new CustomRedisConfig();
        RedisURI redisUri = RedisURI.Builder.redis(cc.REDIS_HOST, cc.REDIS_PORT).withPassword(cc.AUTH).withDatabase(1).build();
        RedisClient client = RedisClient.create(redisUri);

        // 创建StatefulRedisConnection对象
        StatefulRedisConnection<String, String> connection = client.connect();

        // 获取同步的RedisCommands对象
        RedisCommands<String, String> commands = connection.sync();

        long expireSeconds = getSecondsUntilMidnight();

        // 执行Redis命令
        commands.setex(KEY_NAME_PRE + tenantCode + userCode, expireSeconds, maxCode);

        // 关闭连接
        connection.close();
        client.shutdown();

    }

    public synchronized static String getNewCode(String tenantCode, String userCode) {
        CustomRedisConfig cc = new CustomRedisConfig();
        RedisURI redisUri = RedisURI.Builder.redis(cc.REDIS_HOST, cc.REDIS_PORT).withPassword(cc.AUTH).withDatabase(1).build();
        RedisClient client = RedisClient.create(redisUri);

        // 创建StatefulRedisConnection对象
        StatefulRedisConnection<String, String> connection = client.connect();

        // 获取同步的RedisCommands对象
        RedisCommands<String, String> commands = connection.sync();

        Long id = commands.incr(KEY_NAME_PRE + tenantCode + userCode);

        // 关闭连接
        connection.close();
        client.shutdown();

        String formattedNumber = String.format("%06d", id); // 补全ID数字到6位

        LocalDate currentDate = LocalDate.now();

        // 格式化日期为6位时间
        String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyMMdd"));

        tenantCode = tenantCode.substring(1);
        userCode = userCode.substring(1);

        String jadeCode = tenantCode + userCode + formattedDate + formattedNumber;

        return jadeCode;
    }

    // 获取距离今天凌晨0点的剩余秒数
    private long getSecondsUntilMidnight() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime midnight = now.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        Duration duration = Duration.between(now, midnight);
        return duration.getSeconds();
    }
}
